package org.orion.engine;

import java.nio.Buffer;
import java.nio.FloatBuffer;

import javax.media.opengl.GL;

import org.orion.engine.math.Vector3d;

import com.sun.opengl.util.BufferUtil;

public class Mesh {
	protected Buffer data;
	protected int type;
	protected int mode = GL.GL_TRIANGLES;
	protected int count;
	protected Texture texture; 
	protected Vector3d position = new Vector3d();
	protected Vector3d scale = new Vector3d(1.0, 1.0, 1.0);
	private FloatBuffer matrix;//
	
	public Mesh(int type){
		this.type = type;
		this.count = 3;
	}	
	
	public Mesh(int type,Buffer data){
		this.type = type;
		this.setData(data);
	}	
	
	public Mesh(int type,int mode,Buffer data){
		this.type = type;
		this.mode = mode;
		this.setData(data);
	}	
	
	protected final void glPushModelView(){
		matrix = BufferUtil.newFloatBuffer(16);
		matrix.rewind();
		GLStatic.gl.glGetFloatv(GL.GL_MODELVIEW_MATRIX, matrix);
	}
	
	protected final void glModelView(){
		GLStatic.gl.glMatrixMode(GL.GL_MODELVIEW);
		GLStatic.gl.glScaled(scale.x, scale.y, scale.z);
		GLStatic.gl.glTranslated(position.x, position.y, position.z);
	}
	
	protected final void glPopModelView(){
		GLStatic.gl.glLoadMatrixf(matrix);
	}
	
	public void  draw() {
		glPushModelView();
		glModelView();
		if (texture!=null){
			texture.glBind();
		}
		if (data!=null){
			GLStatic.gl.glInterleavedArrays(type, 0, data);
			GLStatic.gl.glDrawArrays(mode, 0, count);
		}
		glPopModelView();
	}
	
	private int typeToSize(int type){
		if (type == GL.GL_V3F){
			return 3;
		}
		if (type == GL.GL_T2F_V3F){
			return 5;
		}
		if (type == GL.GL_T2F_N3F_V3F){
			return 8;
		}
		return 3;
	}
	
	public Texture getTexture() {
		return texture;
	}

	public void setTexture(Texture texture) {
		this.texture = texture;
	}

	public Buffer getData() {
		return data;
	}

	public void setData(Buffer data) {
		this.data = data;
		if (data!=null){
			this.count = data.capacity()/typeToSize(type);
		}
	}

	public int getType() {
		return type;
	}

	public int getMode() {
		return mode;
	}

	public int getCount() {
		return count;
	}

	public Vector3d getPosition() {
		return position;
	}

	public void setPosition(Vector3d position) {
		this.position = position;
	}

	public Vector3d getScale() {
		return scale;
	}

	public void setScale(Vector3d scale) {
		this.scale = scale;
	}

	

	
	
	
}
